package com.financing.wap.util;

/**
 * 示例说明
 * 
 * HelloOSS是OSS Java SDK的示例程序，您可以修改endpoint、accessKeyId、accessKeySecret、bucketName后直接运行。
 * 运行方法请参考README。
 * 
 * 本示例中的并不包括OSS Java SDK的所有功能，详细功能及使用方法，请参看“SDK手册 > Java-SDK”，
 * 链接地址是：https://help.aliyun.com/document_detail/oss/sdk/java-sdk/preface.html?spm=5176.docoss/sdk/java-sdk/。
 * 
 * 调用OSS Java SDK的方法时，抛出异常表示有错误发生；没有抛出异常表示成功执行。
 * 当错误发生时，OSS Java SDK的方法会抛出异常，异常中包括错误码、错误信息，详细请参看“SDK手册 > Java-SDK > 异常处理”，
 * 链接地址是：https://help.aliyun.com/document_detail/oss/sdk/java-sdk/exception.html?spm=5176.docoss/api-reference/error-response。
 * 
 * OSS控制台可以直观的看到您调用OSS Java SDK的结果，OSS控制台地址是：https://oss.console.aliyun.com/index#/。
 * OSS控制台使用方法请参看文档中心的“控制台用户指南”， 指南的来链接地址是：https://help.aliyun.com/document_detail/oss/getting-started/get-started.html?spm=5176.docoss/user_guide。
 * 
 * OSS的文档中心地址是：https://help.aliyun.com/document_detail/oss/user_guide/overview.html。
 * OSS Java SDK的文档地址是：https://help.aliyun.com/document_detail/oss/sdk/java-sdk/install.html?spm=5176.docoss/sdk/java-sdk。
 * 
 */

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.financing.wap.dto.DstUserInfoExpandDTO;

public class AliyunOssUtil {
	static Logger logger = Logger.getLogger(AliyunOssUtil.class);

	// endpoint是访问OSS的域名。如果您已经在OSS的控制台上 创建了Bucket，请在控制台上查看域名。
	// 如果您还没有创建Bucket，endpoint选择请参看文档中心的“开发人员指南 > 基本概念 > 访问域名”，
	// 链接地址是：https://help.aliyun.com/document_detail/oss/user_guide/oss_concept/endpoint.html?spm=5176.docoss/user_guide/endpoint_region
	// endpoint的格式形如“http://oss-cn-hangzhou.aliyuncs.com/”，注意http://后不带bucket名称，
	// 比如“http://bucket-name.oss-cn-hangzhou.aliyuncs.com”，是错误的endpoint，请去掉其中的“bucket-name”。
	private static String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";

	// accessKeyId和accessKeySecret是OSS的访问密钥，您可以在控制台上创建和查看，
	// 创建和查看访问密钥的链接地址是：https://ak-console.aliyun.com/#/。
	// 注意：accessKeyId和accessKeySecret前后都没有空格，从控制台复制时请检查并去除多余的空格。
	private static String accessKeyId = "0TSTGXWQxOZO1Tep";
	private static String accessKeySecret = "IgroUgZjaJET8e9nihAsqlI47L4UGE";

	// Bucket用来管理所存储Object的存储空间，详细描述请参看“开发人员指南 > 基本概念 > OSS基本概念介绍”。
	// Bucket命名规范如下：只能包括小写字母，数字和短横线（-），必须以小写字母或者数字开头，长度必须在3-63字节之间。
	private static String bucketName = "sfacdn";

	// Object是OSS存储数据的基本单元，称为OSS的对象，也被称为OSS的文件。详细描述请参看“开发人员指南 > 基本概念 >
	// OSS基本概念介绍”。
	// Object命名规范如下：使用UTF-8编码，长度必须在1-1023字节之间，不能以“/”或者“\”字符开头。
//	private static String firstKey = "my-first-key";

	private static OSSClient ossClient;

	private static OSSClient getClient() {
		if (ossClient == null) {
			ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		}
		return ossClient;

	}

	public static String writeImgFileImg(InputStream is, String key) {
		ObjectMetadata om = new ObjectMetadata();
		om.setContentType("image/jpeg");
		getClient().putObject(bucketName, key, is,om );
		return key;
	}

	public static String writeFile(InputStream is, String key) {
		if(is == null )
			return null;
		logger.info("AliyunOssUtil writeFile  key:"+key);
		getClient().putObject(bucketName, key, is);
		return key;
	}

	public static void readFile(String key, OutputStream outputStream) throws IOException {

		logger.info("AliyunOssUtil void readFile  key:"+key);
		OSSObject ossObject = getClient().getObject(bucketName,key);
		InputStream inputStream = ossObject.getObjectContent();
		byte[] byteBuffer = new byte[1024 * 4];
		int length = 0;
		while ((length = inputStream.read(byteBuffer)) > 0) {
			outputStream.write(byteBuffer, 0, length);
		}
		inputStream.close();
		outputStream.flush();
		outputStream.close();
		return;
	}
	public static InputStream readFile(String key) throws IOException {
		logger.info("AliyunOssUtil InputStream readFile  key:"+key);
		OSSObject ossObject = getClient().getObject(bucketName,key);
		return ossObject.getObjectContent();
	}

	public static Boolean doesObjectExist(String key) throws IOException {

		logger.info("AliyunOssUtil void doesObjectExist  key:"+key);
		boolean found = getClient().doesObjectExist(bucketName,key);
		
		return found;
	}

	public static void main(String[] args) throws Exception {
		
//		String bImage="/downWechat/test/admindefault/20190522/admindefault_1558517618820.jpg";
//		String cImage="/downWechat/test/shearedImage/20190522/KOTiOdEuxWjDYh0uhngxiVaM3bQl_vgRYm7dkjK6P8mqUTK6k0cvRwxHNeAGTAM5_1558510596252.jpg";
//		String tePath="/disk/upload/watertemp/111.jpg";
//		String tPath="downWechat/test/shearedImage/test/marktest.jpg";
//	
//		markPoster(bImage, cImage, tePath, tPath);
//		
//		
//		System.exit(0);
		//背景图
		String backGroudImage="downWechat/test/mark2.jpg";
//		System.out.println(doesObjectExist(backGroudImage));
		//目标
		String targetPath = "downWechat/test/shearedImage/test/marktest.jpg";
		//名片地址                             
		String cardImage = "downWechat/test/shearedImage/userShareRegister/20190528/ouBOIt1rXyc8Bmffg8mJ4ltZa94k_.jpg";
//		String cardImage="downWechat/test/shearedImage/20190523/XVmPhP_ffI7YFPitppr2ytIiZ29fpMoeEdqOWgJdaFqKqNibTsfAU6VfpRfdIY4X_1558596617962.jpg";
		//缓存地址
		String tempPath = "/disk/upload/watertemp/111.jpg";
		// 头像指定目录环境
		String headTemp = "downWechat/test/tempHeadImage/111.jpg";
		//头像地址
		String headImageurl = "http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoBKMhalMKwtVxItEhhib7ZQIUI19lrcmLU06kc5A2SKmsLV2fIvticd9Nlfhic56eIWsVhKhlZdnjew/132";
		
		markRegister(backGroudImage, cardImage, tempPath,headTemp,headImageurl, targetPath);
		
		
		
		
		DstUserInfoExpandDTO dto=new DstUserInfoExpandDTO();
		dto.setUserPhone("上海浦东新区福山路450号新天国际大厦28楼cd大厦");
		if(StringUtils.isBlank(dto.getUserName())){
			dto.setUserName("上海浦东新区福山路450号新天国际大厦28楼cd大厦");
		}
		if(StringUtils.isBlank(dto.getUserPosition())){
			dto.setUserPosition("我们的生活方式是什么时候我的活方式是什什什");
		}
		if(StringUtils.isBlank(dto.getUserEmail())){
			dto.setUserEmail("guozongxunuudjskajidj359jkfjssjksjdf@sup11serfa.cn");
		}
		if(StringUtils.isBlank(dto.getUserCompany())){
			dto.setUserCompany("上海浦东新区福山路450号新天国际大厦28楼cd大厦");
		}
		if(StringUtils.isBlank(dto.getUserAddress())){
			dto.setUserAddress("上海浦东新区福山路450号新天楼cdf");
		}
//		markUserCard(backGroudImage, targetPath, cardImage, tempPath, headTemp, headImageurl,dto);
	
		/*
		 * FileOutputStream fileOutputStream = new FileOutputStream(new
		 * File("D:\\test\\123.mp3"));
		 * AliyunOssUtil.readFile(key,fileOutputStream);
		 */

		logger.info("Completed");
	}
	/***
	 * 生成用户名片
	 * @param backGroudImage   背景
	 * @param targetPath   目标
	 * @param cardImage   名片二维码图片
	 * @param tempPath    缓存目录(local)
	 * @param headTemp    头像缓存目标(oss)
	 * @param headImageurl   用户头像地址
	 * @param 文字内容
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static void markUserCard(String backGroudImage, String targetPath,
			String cardImage, String tempPath, String headTemp,
			String headImageurl,DstUserInfoExpandDTO dto) throws Exception {
		
		File f = new File(tempPath);
		File fileParent = f.getParentFile();  
		if(!fileParent.exists()){
			fileParent.mkdirs();
		}
		logger.info("backGroudImage:"+backGroudImage);
		logger.info("cardImage:"+cardImage);
		//第一个为/  需要删除
		if(cardImage.startsWith("/")){
			cardImage=cardImage.substring(1);
		}
		//微信头像压缩至oss
		if(!AliyunOssUtil.doesObjectExist(headTemp)){
			logger.info("headTemp 不存在");
			BufferedImage zoomOutImage = ImageMarkLogoByIconUtil.zoomOutImage(
					ImageIO.read(RequstUtil.doRequestStream(headImageurl)), 120, 120, true);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ImageIO.write(zoomOutImage, "PNG", baos);
			AliyunOssUtil.writeFile(new ByteArrayInputStream(baos.toByteArray()),
					headTemp);
		}
		GetObjectRequest req = new GetObjectRequest(bucketName, backGroudImage);
		String head = Base64.encodeBase64URLSafeString((headTemp).getBytes());
		String s = "image/watermark,image_" + head + ",g_nw,x_60,y_60";
		
		if(StringUtils.isNotBlank(cardImage)){
			String cipherImage = Base64
					.encodeBase64URLSafeString((cardImage + "?x-oss-process=image/resize,m_pad,w_500,h_500")
							.getBytes());
			s += "/watermark,image_" + cipherImage + ",t_100,g_south,y_240";
		}
		String cipherImage = Base64.encodeBase64URLSafeString(subStr(dto.getUserName(),20).getBytes());
		s += "/watermark,text_" + cipherImage + ",g_nw,x_200,y_80,size_42";
		if(StringUtils.isNotBlank(dto.getUserPhone())){
			cipherImage = Base64.encodeBase64URLSafeString(dto.getUserPhone().getBytes());
			s += "/watermark,text_" + cipherImage + ",g_nw,x_200,y_140,color_3c9af2,size_24";
		}
		cipherImage = Base64.encodeBase64URLSafeString(subStr(dto.getUserPosition(),20).getBytes());
		s += "/watermark,text_" + cipherImage + ",g_nw,x_120,y_215,size_24";
		//邮箱 40
		int emailCount=StringUtil.isEmail(dto.getUserEmail())?55:20;
		cipherImage = Base64.encodeBase64URLSafeString(subStr(dto.getUserEmail(),emailCount).getBytes());
		s += "/watermark,text_" + cipherImage + ",g_nw,x_120,y_255,size_24";
		cipherImage = Base64.encodeBase64URLSafeString(subStr(dto.getUserCompany(),20).getBytes());
		s += "/watermark,text_" + cipherImage + ",g_nw,x_120,y_295,size_24";
		cipherImage = Base64.encodeBase64URLSafeString(subStr(dto.getUserAddress(),20).getBytes());
		int y=dto.getUserAddress().length()>20?335:340;
		s += "/watermark,text_" + cipherImage + ",g_nw,x_120,y_"+y+",size_24";
		if(dto.getUserAddress().length()>20){
			cipherImage = Base64.encodeBase64URLSafeString(subStr(dto.getUserAddress().substring(20),20).getBytes());
			s += "/watermark,text_" + cipherImage + ",g_nw,x_120,y_370,size_24";
		}
		req.setProcess(s);
		getClient().getObject(req, f);
		// 处理头像
		writeFile(new FileInputStream(f), targetPath);
		f.delete();
	}
	
	
	/***
	 * 生成海报
	 * @param backGroudImage   背景
	 * @param cardImage 二维码
	 * @param 本地缓存
	 * @param targetPath   目标
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static void markPoster(String backGroudImage, String cardImage,
			String tempPath, String targetPath) throws Exception {
		
		//第一个为/  需要删除
		if(backGroudImage.startsWith("/")){
			backGroudImage=backGroudImage.substring(1);
		}
		if(cardImage.startsWith("/")){
			cardImage=cardImage.substring(1);
		}
		File f = new File(tempPath);
		File fileParent = f.getParentFile();
		if (!fileParent.exists()) {
			fileParent.mkdirs();
		}
		logger.info("backGroudImage:" + backGroudImage);
		logger.info("cardImage:" + cardImage);
		GetObjectRequest req = new GetObjectRequest(bucketName, backGroudImage);
		String cipherImage = Base64
				.encodeBase64URLSafeString((cardImage + "?x-oss-process=image/resize,w_160,h_160")
						.getBytes());
		String s = "image/watermark,image_" + cipherImage + ",t_100,g_se,y_20,x_20";
		req.setProcess(s);
		getClient().getObject(req, f);
		// 处理头像
		writeFile(new FileInputStream(f), targetPath);
		f.delete();
	}
	
	/***
	 * 生成邀请注册图
	 * @param backGroudImage 背景
	 * @param cardImage 二维码
	 * @param headTemp 头像缓存地址
	 * @param headImageurl 头像地址
	 * @param 本地缓存
	 * @param targetPath   目标
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static void markRegister(String backGroudImage, String cardImage,
			String tempPath, String headTemp,
			String headImageurl, String targetPath) throws Exception {
		
		//第一个为/  需要删除
		if(backGroudImage.startsWith("/")){
			backGroudImage=backGroudImage.substring(1);
		}
		if(cardImage.startsWith("/")){
			cardImage=cardImage.substring(1);
		}
		//微信头像压缩至oss
		if(!AliyunOssUtil.doesObjectExist(headTemp)){
			logger.info("headTemp 不存在");
			BufferedImage zoomOutImage = ImageMarkLogoByIconUtil.zoomOutImage(
					ImageIO.read(RequstUtil.doRequestStream(headImageurl)), 120, 120, true);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ImageIO.write(zoomOutImage, "PNG", baos);
			AliyunOssUtil.writeFile(new ByteArrayInputStream(baos.toByteArray()),
					headTemp);
		}
		GetObjectRequest req = new GetObjectRequest(bucketName, backGroudImage);
		String head = Base64.encodeBase64URLSafeString((headTemp).getBytes());
		String s = "image/watermark,image_" + head + ",g_north,x_60,y_60";
		
		File f = new File(tempPath);
		File fileParent = f.getParentFile();
		if (!fileParent.exists()) {
			fileParent.mkdirs();
		}
		logger.info("backGroudImage:" + backGroudImage);
		logger.info("cardImage:" + cardImage);
		String cipherImage = Base64
				.encodeBase64URLSafeString((cardImage + "?x-oss-process=image/resize,w_330,h_330")
						.getBytes());
		s += "/watermark,image_" + cipherImage + ",t_100,g_south,x_10,y_148";
		req.setProcess(s);
		getClient().getObject(req, f);
		// 处理头像
		writeFile(new FileInputStream(f), targetPath);
		f.delete();
	}
	
	
	public static String subStr(String str,int x){
		if(StringUtils.isBlank(str))return "";
		
		if(str.length()>x){
			return str.substring(0,x);
		}else{
			return str;
		}
	}
}


